package com.seeyon.bugfixtools.form.dao;

import com.seeyon.bugfixtools.form.dto.FormBizInfo;
import org.springframework.context.annotation.Lazy;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * 应用包
 */
@Repository
public class FormDao {

    private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(FormDao.class);

    @Lazy
    @Resource
    private JdbcTemplate jdbcTemplate;

    /**
     * 获取有问题的权限数据
     *
     * @return
     */
    public FormBizInfo getFormBizInfoByFormId(String formId) {
        if (formId == null || formId.trim().isEmpty()) {
            // 输入验证：避免空或空白的formId
            throw new IllegalArgumentException("Form ID cannot be null or empty.");
        }

        String sql = "SELECT biz.id AS bizId,biz.NAME AS bizName,bi.FORMID AS formId,f.NAME formName " +
                "FROM cap_form_definition f " +
                "LEFT JOIN cap_biz_config_item bi ON bi.FORMID=f.id " +
                "LEFT JOIN cap_biz_config biz ON bi.BIZID=biz.id WHERE f.id= ? ";

        try {
            return jdbcTemplate.queryForObject(sql, new FormBizInfoRowMapper(), formId);
        } catch (DataAccessException e) {
            // 异常处理：记录或抛出更具体的异常信息
            logger.error("查询表单对应应用包信息出错", e);
            throw new RuntimeException("Error fetching form biz info: " + e.getMessage());
        }
    }


    private static class FormBizInfoRowMapper implements RowMapper<FormBizInfo> {
        @Override
        public FormBizInfo mapRow(ResultSet rs, int rowNum) throws SQLException {
            FormBizInfo info = new FormBizInfo();
            info.setBizId(rs.getString("bizId"));
            info.setBizName(rs.getString("bizName"));
            info.setFormId(rs.getString("formId"));
            info.setFormName(rs.getString("formName"));
            return info;
        }
    }

}
